package com.tucc.hello.leetcode.no1_400.no1_200.no41_60.no43;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        String num1 = "5", num2 = "953214";
        String result = solution.multiply(num1, num2);
        System.out.println(result);

        System.out.println(result.equals("" + (Long.valueOf(num1) * Long.valueOf(num2))));
    }

    public static final String ZERO_STR = "0";
    public static final String ONE_STR = "1";
    public static final char ZERO_CHAR = '0';
    public static final int TEN = 10;

    public String multiply(String num1, String num2) {
        if (ZERO_STR.equals(num1) || ZERO_STR.equals(num2)) {
            return ZERO_STR;
        }
        if (ONE_STR.equals(num1)) {
            return num2;
        } else if (ONE_STR.equals(num2)) {
            return num1;
        }
        if (num1.length() > num2.length()) {
            return multiply(num2, num1);
        }
        List<String> nums = new ArrayList<>();
        int addition = 0;
        int nl1 = num1.length(), nl2 = num2.length();
        for (int i = nl1 - 1; i >= 0; i--) {
            int sum = 0;
            StringBuilder temp = new StringBuilder();
            int n1 = num1.charAt(i) - ZERO_CHAR;
            for (int j = nl2 - 1; j >= 0; j--) {
                int n2 = (num2.charAt(j) - ZERO_CHAR);
                sum = n1 * n2;
                sum += addition;
                addition = sum / TEN;
                temp.append(sum % TEN);
            }
            if (addition != 0) {
                temp.append(addition);
                addition = 0;
            }
            temp = temp.reverse();
            for (int k = i; k < nl1 - 1; k++) {
                temp.append(0);
            }
            nums.add(temp.toString());
        }
        return addNums(nums);
    }

    public String addNums(List<String> nums) {
        StringBuilder result = new StringBuilder();
        int addition = 0;
        int index = 1;
        while (!nums.isEmpty()) {
            Iterator<String> iterator = nums.iterator();
            int sum = 0;
            while (iterator.hasNext()) {
                String num = iterator.next();
                char ch = num.charAt(num.length() - index);
                sum += ch - ZERO_CHAR;
                if (num.length() <= index) {
                    iterator.remove();
                }
            }
            sum += addition;
            addition = sum / TEN;
            result.append(sum % TEN);
            index++;
        }
        if (addition != 0) {
            result.append(addition);
        }
        return result.reverse().toString();
    }

}
